﻿
namespace TestFsWeb

open System
open System.Net
open System.IO
open System.Text
open Microsoft.FSharp.Control.WebExtensions

module WebRequestResponseExtend =

    type WebRequest with 
        member this.AsyncGetRequestStream() =
            Async.FromBeginEnd(this.BeginGetRequestStream,this.EndGetRequestStream)

        member this.AsyncPost (text:string,?optContentType:string) =
            this.Method <- "POST"
            this.ContentType <- defaultArg optContentType "text/html; charset=UTF-8"

            let bytes = Encoding.UTF8.GetBytes text
            this.ContentLength <- int64 bytes.Length

            async {
                use! postStream = this.AsyncGetRequestStream()
                do! postStream.AsyncWrite bytes
            }

        member this.AsyncGetResponseString() = async {
            use! response = this.AsyncGetResponse()
            use responseReader = new StreamReader(response.GetResponseStream() )
            return! responseReader.AsyncReadToEnd()
        }


